package com.e3.basdoc.tax.service.impl;

import java.util.List;

import com.e3.basdoc.tax.dao.TaxDAO;
import com.e3.basdoc.tax.entity.TaxEntity;
import com.e3.basdoc.tax.model.TaxModel;
import com.e3.basdoc.tax.service.TaxCacheManager;
import com.e3.basdoc.tax.service.TaxService;
import com.e3.core.base.DAOHelper;
import com.e3.core.base.ServiceException;
import com.e3.core.base.SuperService;

public class TaxServiceImpl extends SuperService implements TaxService{
	
	private TaxDAO taxDAO;
	
	private TaxDAO getTaxDAO(){
		if(taxDAO == null){
			taxDAO = DAOHelper.createDAOInstance(TaxDAO.class);
		}
		return taxDAO;
	}

	public TaxModel newTax(TaxModel model) throws ServiceException {
		validateTax(model);
		checkTaxExisted(model);
		
		TaxEntity entity = taxModelToEntity(model, null);
		getTaxDAO().persist(entity);
		
		model.setId(entity.getId());
		
		TaxCacheManager.INSTANCE.put(model);
		
		return model;
	}

	public TaxModel modifyTax(TaxModel model) throws ServiceException {
		validateTax(model);
		
//		String strId = model.getId();
//		long id = Long.parseLong(strId == null ? "0" : strId);
		
		long id  = model.getId();

		TaxEntity entity = getTaxDAO().getById(TaxEntity.class, id);
		if (entity == null) {
			return newTax(model);
		}

		String oldCode = entity.getCode();
		if (!oldCode.equals(model.getCode())) {
			checkTaxExisted(model);
		}

		taxModelToEntity(model, entity);
		getTaxDAO().merge(entity);
		
		TaxCacheManager.INSTANCE.put(model);
		return model;
	}

	public void deleteTaxByIds(List<Long> ids) throws ServiceException {
		if(ids == null||ids.isEmpty()){
			return;
		}
		
		getTaxDAO().deleteTaxByIds(ids);
		
		TaxCacheManager.INSTANCE.remove(ids);
	}

	public void checkTaxExisted(TaxModel model) throws ServiceException {
		if (model == null) {
			return;
		}

		String code = model.getCode();
		String name = model.getName();
		
		StringBuffer msgs = new StringBuffer();
		long size = getTaxDAO().getTaxSizeByCode(code);
		if(size>0){
			msgs.append("编码为'" + code+"' ");
		}
		size = getTaxDAO().getTaxSizeByName(name);
		if (size>0) {
			msgs.append("名称为'" + name + "' ");
		}
		if(msgs.length()>0){
			msgs.append("已经存在，请设置新的编码和名称。");
			throw new ServiceException(msgs.toString());
		}
	}

	private void validateTax(TaxModel model) throws ServiceException{
		String code = model.getCode();
		String name = model.getName();
		//double rate = model.getRate();

		if (code == null || code.trim().length() == 0 
			|| name == null || name.trim().length() == 0
			) {
			throw new ServiceException("请设置编码,名称和税率。");
		}
	}
	
	private TaxEntity taxModelToEntity(TaxModel model,TaxEntity entity){
		entity = modelToEntity(TaxEntity.class, model, entity);

		entity.setCode(model.getCode());
		entity.setName(model.getName());
		entity.setRate(model.getRate()==null?0:model.getRate());
		
		return entity;

	}
}
